package com.javabi.codegenerator.java.object.executable.method;

import java.io.IOException;
import java.util.List;

import com.javabi.codegenerator.java.model.bean.JavaModelBean;
import com.javabi.codeobject.java.block.codeblock.IJavaCodeLines;
import com.javabi.codeobject.java.block.codeblock.JavaCodeLines;
import com.javabi.codeobject.java.block.method.JavaMethod;
import com.javabi.codeobject.java.type.IJavaType;
import com.javabi.codetype.serializer.data.IDataWriter;

public class WriteObjectMethod extends JavaMethod {

	private final List<JavaModelBean> beanList;

	public WriteObjectMethod(IJavaType beanType, List<JavaModelBean> beanList) {
		super("writeObject");
		this.beanList = beanList;
		getParameters().add("writer", IDataWriter.class);
		getParameters().add("bean", beanType);
		getThrowsSet().add(IOException.class);
		setOverride();

		setMethodContents();
	}

	private void setMethodContents() {
		IJavaCodeLines code = new JavaCodeLines();
		code.line("int id = bean.getSerializationId();");
		code.line("writer.writePositiveInteger(id);");
		code.line("switch (id) {");
		for (JavaModelBean bean : beanList) {
			getReferences().add(bean.getInterfaceType());
			getReferences().add(bean.getDataSerializer().getType());

			String serializerName = bean.getDataSerializer().getName();
			String interfaceName = bean.getInterfaceType().getSimpleName(true);

			code.line(1, "case " + interfaceName + ".SERIALIZATION_ID:");
			code.line(2, "new " + serializerName + "().writeObject(writer, (" + interfaceName + ") bean);");
			code.line(2, "return;");
		}
		code.line(1, "default:");
		code.line(2, "throw new IllegalArgumentException(\"Bean id not supported: \" + id);");
		code.line("}");
		setContents(code);
	}
}
